import { asyncRouterMap, constantRouterMap } from '@/router'
// import { findMenuByRoleId } from '@/api/menu'
import { switchMap, tap } from 'rxjs/operators'

function filterAsyncRouter(asyncRouterMap, pathList) {
  const keys = Array.from(pathList.keys())
  return asyncRouterMap.filter(route => {
    return keys.some(key => {
      if (key === route.path.slice(1)) {
        if (route.children && route.children.length) {
          route.children = route.children
            .filter(child => {
              if (child.path === '') {
                return true
              } else {
                const childPaths = Array.from(pathList.get(key).keys())
                return childPaths.some(childPath => childPath === child.path)
              }
            })
            .map(child => {
              child.props = { id: pathList.get(key).get(child.path || 'index') }
              return child
            })
        }
        return true
      } else {
        return false
      }
    })
  })
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, { roles }) {
      return new Promise(resolve => {
        from(roles)
          .pipe(
            switchMap(async role => {
              const res = await findMenuByRoleId(role.userRoleId)
              return res.role.menus.map(({ path, menu_id }) => ({
                path: path.slice(1).split('/'),
                id: menu_id
              }))
            }),
            tap(value => {
              const pathList = new Map()
              value.forEach(({ path, id }) => {
                if (pathList.has(path[0])) {
                  pathList.get(path[0]).set(path[1], id)
                } else {
                  pathList.set(path[0], new Map([[path[1] || 'index', id]]))
                }
              })
              // let accessedRouters = asyncRouterMap
              // if (roles.find(({ role_name }) => role_name === 'admin')) {
              //   // accessedRouters = filterAsyncRouter(asyncRouterMap, pathList)
              //   accessedRouters = asyncRouterMap
              // } else {
              //   accessedRouters = filterAsyncRouter(asyncRouterMap, pathList)
              // }
              commit('SET_ROUTERS', asyncRouterMap)
            })
          )
          .subscribe(() => {
            resolve()
          })
      })
    }
  }
}

export default permission
